package jp.joogoo.web.controller;

import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Logger;

import jp.joogoo.web.meta.M_joogooMeta;
import jp.joogoo.web.model.M_joogoo;
import jp.joogoo.web.model.M_service;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.org.json.JSONStringer;

public class JoogoosController extends Controller {
    private static final Logger logger = Logger
        .getLogger(JoogoosController.class.getName());
    private static final M_joogooMeta meta = new M_joogooMeta();

    @Override
    protected Navigation run() throws Exception {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        JSONStringer jsonJoogoos = new JSONStringer();
        if (user != null) {
            logger.info("user" + user.getEmail());

            List<M_joogoo> joogoos =
                Datastore
                    .query(meta)
                    .filter(meta.userId.equal(user.getUserId()))
                    .asList();
            jsonJoogoos.array();
            if (joogoos != null && joogoos.size() > 0) {
                for (M_joogoo joogoo : joogoos) {
                    M_service service = joogoo.getMServiceRef().getModel();
                    jsonJoogoos
                        .object()
                        .key("key")
                        .value(KeyFactory.keyToString(joogoo.getKey()))
                        .key("name")
                        .value(service.getServiceName())
                        .endObject();
                }
            }
            jsonJoogoos.endArray();

        } else {
            jsonJoogoos.object().key("error").value("ログインしていません").endObject();
        }

        logger.info("response:" + jsonJoogoos.toString());
        PrintWriter writer = response.getWriter();
        writer.print(jsonJoogoos.toString());

        response.flushBuffer();

        return null;
    }

}
